package models.my;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import models.user.UserInfo;

import play.Logger;
import play.db.ebean.Model;
import tyrex.services.UUID;
import utils.MengException;
//15
/**
 * 我的动态信息列表
 * @author zhangpeng
 *
 */

@Entity
@Table(name="my_dynamic")
public class MyDynamic extends Model{

	private static final long serialVersionUID = 1L;
	
	@Id
	public long id;
	public String code = UUID.create();
	public String username;
	public String friend;
	public String posts_code;
	
	public static MyDynamic getInstances(){
		return new MyDynamic();
	}
	
	public static Model.Finder<Long, MyDynamic> find = new Model.Finder<Long, MyDynamic>(Long.class, MyDynamic.class);
	
	/**
	 * 创建用户动态
	 * 
	 * @param dynamic
	 * @return
	 * @throws MengException
	 */
	public boolean createDynamic(MyDynamic dynamic) throws MengException {

		if (UserInfo.getInstances().verifyUsername(dynamic.username)) {
			throw new MengException("150001", "用户名不存在");
		}

		if (verifyMyDynamic(dynamic.posts_code)) {
			throw new MengException("150002", "用户动态已存在");
		}

		try {
			dynamic.save();
			return true;
		} catch (Throwable t) {
			t.printStackTrace();
			Logger.error("UserInfo createDynamic Exception," + t.getMessage());
			throw new MengException("150003", "用户动态保存失败");
		}
	}
	
	/**
	 * 删除用户动态
	 * @param code
	 * @return
	 * @throws MengException
	 */
	public boolean destroyDynamic(String code) throws MengException {
		
		try {
			getDynamic(code).delete();
			return true;
		} catch (Throwable t) {
			t.printStackTrace();
			Logger.error("UserInfo createDynamic Exception," + t.getMessage());
			throw new MengException("150003", "删除用户动态失败");
		}
	}
	
	/**
	 * 获取用户动态列表
	 * @param username
	 * @param page
	 * @param size
	 * @return
	 * @throws MengException
	 */
	public List<MyDynamic> getDynamicPage(String username, int page, int size) throws MengException {
		
		try {
			return find.where().eq("username", username).findPagingList(size).getPage(page).getList();
		} catch (Throwable t) {
			t.printStackTrace();
			Logger.error("UserInfo createDynamic Exception," + t.getMessage());
			throw new MengException("150003", "获取用户动态列表失败");
		}
	}
	
	/**
	 * 获取用户动态
	 * @param code
	 * @return
	 * @throws MengException
	 */
	public MyDynamic getDynamic(String code) throws MengException {
		
		try {
			return find.where().eq("code", code).findUnique();
		} catch (Throwable t) {
			t.printStackTrace();
			Logger.error("UserInfo createDynamic Exception," + t.getMessage());
			throw new MengException("150003", "获取用户动态失败");
		}
	}
	
	public boolean verifyMyDynamic(String posts_code) throws MengException {
		MyDynamic dynamic = find.where().eq("posts_code", posts_code).findUnique();
		if( dynamic != null) {
			return true;
		}
		return false;
	}

}
